#include "response_handler.h"
#include <libwebsockets.h>
#include <stdlib.h>
#include <string.h>

void send_json(struct lws *wsi, struct json_object *json) {
    const char *response_str = json_object_to_json_string(json);
    size_t len = strlen(response_str);
    
    unsigned char *buf = malloc(LWS_PRE + len + 1);
    if (!buf) {
        json_object_put(json);
        return;
    }
    
    memcpy(buf + LWS_PRE, response_str, len);
    lws_write(wsi, buf + LWS_PRE, len, LWS_WRITE_TEXT);
    free(buf);
    json_object_put(json);
}

void send_response(struct lws *wsi, const char *action, 
                   const char *status, const char *message) {
    struct json_object *response = json_object_new_object();
    json_object_object_add(response, "action", json_object_new_string(action));
    json_object_object_add(response, "status", json_object_new_string(status));
    
    if (message) {
        json_object_object_add(response, "message", json_object_new_string(message));
    }
    
    send_json(wsi, response);
}

void send_secret_key(struct lws *wsi, const char *action, 
                     const char *status, const char *secret_key) {
    struct json_object *response = json_object_new_object();
    json_object_object_add(response, "action", json_object_new_string(action));
    json_object_object_add(response, "status", json_object_new_string(status));
    
    if (secret_key) {
        json_object_object_add(response, "secretKey", json_object_new_string(secret_key));
    }
    
    send_json(wsi, response);
}